package handlers

import (
	"cnagku/cache"
	"cnagku/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var goods []models.Goods
	redis_key := "list_" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Offset(offset).Limit(size).Find(goods)
		jsonData, _ := json.Marshal(goods)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &goods)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": goods,
	})
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var goods models.Goods
	redis_key := "detail_" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Where("id=?", id).Find(goods)
		jsonData, _ := json.Marshal(goods)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &goods)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": goods,
	})
}
